package com.example.newhabitclock.CalendarView

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.example.newhabitclock.MainViewModel
import com.example.newhabitclock.databinding.FragmentCalendarItemBinding
import com.prolificinteractive.materialcalendarview.CalendarDay
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

//用于显示打卡日历界面recyclerView的item界面,每个习惯对应一个item用一个界面显示
class CalendarItemFragment : Fragment() {
    private lateinit var binding: FragmentCalendarItemBinding
    private val viewModel: MainViewModel by activityViewModels()
    private var habitId: Int? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentCalendarItemBinding.inflate(layoutInflater)
        habitId = arguments?.getInt("HABIT_ID")
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        habitId?.let { id ->
            // 观察习惯名称
            viewModel.getHabitById(id).observe(viewLifecycleOwner) { habit ->
                habit?.let {
                    binding.habitName.text = it.name
                }
            }

            // 观察打卡日期（使用正确的id变量）
            viewModel.getCheckInDates(id).observe(viewLifecycleOwner) { dates ->
                //字符串日期转换为 CalendarDay 对象集合
                val calendarDays = convertDateStringsToCalendarDays(dates)
                Log.d("pxd", "Received dates: $dates")
                //清除旧的装饰器
                binding.materialCalendarView.removeDecorators()
                //添加新的装饰器
                if (calendarDays.isNotEmpty()){
                    binding.materialCalendarView.addDecorator(
                        RedCircleDecorator(requireContext(), calendarDays)
                    )
                }
                //强制刷新
                binding.materialCalendarView.invalidateDecorators()
            }
        }
    }

    // 将字符串日期转换为 CalendarDay 的集合（使用 Set 避免重复）
    private fun convertDateStringsToCalendarDays(dateStrings: List<String>): Set<CalendarDay> {
        return dateStrings.mapNotNull { dateString ->
            try {
                val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                val date = sdf.parse(dateString)
                val calendar = Calendar.getInstance().apply { time = date!! }
                CalendarDay.from(calendar)
            } catch (e: Exception) {
                null // 忽略格式错误的日期
            }
        }.toSet()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //释放MaterialCalendarView资源 防止占用太多资源
        binding.materialCalendarView.removeDecorators()
    }

}
